package com.wispx.gateway.core.filter.gray.strategy;

import com.wispx.gateway.config.pojo.RouteDefinition;
import com.wispx.gateway.config.pojo.ServiceInstance;
import com.wispx.gateway.config.util.FilterConfigUtil;
import com.wispx.gateway.core.context.GatewayContext;

import java.util.List;
import java.util.Optional;

import static com.wispx.gateway.common.constant.FilterConstant.GRAY_FILTER_NAME;
import static com.wispx.gateway.common.constant.GrayConstant.CLIENT_IP_GRAY_STRATEGY;
import static com.wispx.gateway.common.constant.GrayConstant.MAX_GRAY_RATIO;

/**
 * 根据客户端IP判断是否走灰度
 */
public class ClientIpGrayStrategy implements GrayStrategy {
    @Override
    public boolean shouldRoute2Gray(GatewayContext context, List<ServiceInstance> instances) {
        if (instances.stream().anyMatch(instance -> instance.isEnable() && !instance.isGray())) {
            RouteDefinition.GaryFilterConfig garyFilterConfig = FilterConfigUtil.findFilterConfigByClass(context.getRouteDefinition().getFilterConfigs(), GRAY_FILTER_NAME, RouteDefinition.GaryFilterConfig.class);
            double maxGrayRatio = instances.stream().mapToDouble(ServiceInstance::getGrayRatio).sum();
            maxGrayRatio = Math.min(maxGrayRatio, Optional.ofNullable(garyFilterConfig.getMaxGrayRadio()).orElse(MAX_GRAY_RATIO));
            // 根据IP判断是否走灰度
            return context.getRequest().getHost().hashCode() % 100 <= maxGrayRatio * 100;
        }
        return false;
    }

    @Override
    public String mark() {
        return CLIENT_IP_GRAY_STRATEGY;
    }
}
